package com.cscec5b.inspection.config;

import com.nimbusds.jose.jwk.RSAKey;
import org.springframework.stereotype.Component;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.UUID;

@Component
public class KeyManager {

    private final RSAPublicKey publicKey;
    private final RSAPrivateKey privateKey;
    private final RSAKey rsaJwk; // 给 /.well-known/jwks.json 用
    private final String keyId;

    public KeyManager() {
        try {
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
            kpg.initialize(2048);
            KeyPair kp = kpg.generateKeyPair();
            this.publicKey = (RSAPublicKey) kp.getPublic();
            this.privateKey = (RSAPrivateKey) kp.getPrivate();
            this.keyId = UUID.randomUUID().toString();
            this.rsaJwk = new RSAKey.Builder(publicKey)
                    .privateKey(privateKey)
                    .keyID(keyId)
                    .build();
        } catch (Exception e) {
            throw new IllegalStateException("init rsa key pair failed", e);
        }
    }

    public RSAPublicKey publicKey() { return publicKey; }
    public RSAPrivateKey privateKey() { return privateKey; }
    public java.security.interfaces.RSAPublicKey publicKey(String kid) {
        // 目前我们只有一把运行时生成的公钥；忽略 kid，直接返回这把公钥
        return publicKey();
    }
    public RSAKey currentJwk() { return rsaJwk; }
    public String keyId() { return keyId; }
}
